package com.ns.main.dao;

import java.util.Iterator;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongoBase {

	private static MongoClient  client;
	private static MongoBase baseDao;
	private static MongoDatabase inDB;
//	private static MongoDatabase queryDB;
	
	public synchronized static  MongoBase getInstance(){
		if(null!=baseDao){
			return baseDao;
		}
		baseDao = new MongoBase();
		client = new MongoClient("localhost");
		inDB = client.getDatabase("novel");
		return baseDao;
	}

	public  void insertMany(String collectionName,List<Document> docs){
		inDB.getCollection(collectionName).insertMany(docs);
	}
	public  void insertOne(String collectionName,Document doc){
		inDB.getCollection(collectionName).insertOne(doc);
	}
	
	
	
	public static void main(String[] args) {
		MongoClient client = new MongoClient("localhost");
		MongoDatabase db = client.getDatabase("test");
//		db.getName();
		System.out.println(db.getName());
		Iterator<Document> dbnames =  db.listCollections().iterator();
		while (dbnames.hasNext()) {
			System.out.println(dbnames.next().getString("name"));
		}
		MongoCollection<Document> xijun = db.getCollection("xijun");
		Document d1 = new Document();
		d1.append("name", "mongo").append("description", "NoSQL DB");
//		xijun.insertOne(d1);
		xijun.updateMany(Filters.eq("name", "mongo"), new Document("$set",new Document("likes",10000)));
		xijun.deleteOne(Filters.eq("name", "mongo"));
		xijun.deleteMany(Filters.eq("name","mongo"));
		
		MongoCursor<Document> all = xijun.find().iterator();
		while (all.hasNext()) {
			System.out.println(all.next().toString());
		}
		client.close();
		
		
	}
}
